package com.thread.wait;

/**
 * @author wangyingjie
 * @date
 * @remark
 */
public class InterruptDemo {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread() {
            @Override
            public void run() {
                int  count = 0;
                while (true){
                    if (currentThread().isInterrupted()){
                        //被标记上中断标志不会马上终止，如果需要马上终止，自己手动退出循环
                        System.out.println("中断。。。。");
                        break;
                    }
                    try {
                        count ++;
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        System.out.println(count);
                        e.printStackTrace();
                        System.out.println("线程堵塞时被中断需要手动捕获异常。。");
                        //抛出异常，操作回滚，interrput()需要重新设置一遍
                        Thread.currentThread().interrupt();
                    }
                    System.out.println("异常出来继续走。。");
                    Thread.yield();
                }
            }
        };

        thread.start();
        //稍微阻塞下，让thread.interrupt()和Thread.sleep()同时进行
        Thread.sleep(1000);
        //加上中断标志，sleep的阻塞线程会抛出异常
        thread.interrupt();
        System.out.println(thread.isInterrupted());
    }
}
